package com.mo.lib.ui.action

import android.app.Activity
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.os.SystemClock
import java.lang.ref.WeakReference

/**
 * @ author：mo
 * @ data：2020/7/20:11:06
 * @ 功能：Handler 意图处理
 */
interface HandlerAction {
    companion object {
        val MainHandler = Handler(Looper.getMainLooper())
    }
    /** 自定义Handler，避免内存泄漏,默认主线程里创建*/
    abstract class MyHandler(val activity: Activity, looper: Looper = Looper.getMainLooper()) : Handler(looper) {
        var weakReference: WeakReference<Activity>? = null
        init {
            weakReference = WeakReference<Activity>(activity)
        }

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            weakReference?.let { it1 ->
                it1.get()?.let {
                    doWhat(it, msg)
                }
            }
        }

        protected abstract fun doWhat(activity: Activity, msg: Message)
    }

    /** 获取 Handler(主线程)*/
    val handler: Handler
        get() = MainHandler

    /** 延迟执行*/
    fun post(runnable: Runnable) = postDelayed(runnable, 0)

    /** 延迟一段时间执行*/
    fun postDelayed(runnable: Runnable, delayMillis: Long) = postAtTime(runnable, SystemClock.uptimeMillis() + if (delayMillis < 0) 0 else delayMillis)

    /**在指定的时间执行 */
    fun postAtTime(runnable: Runnable, uptimeMillis: Long) = handler.postAtTime(runnable, this, uptimeMillis)

    /** 移除当前handler单个消息回调*/
    fun removeCallbacks(runnable: Runnable) {
        MainHandler.removeCallbacks(runnable)
    }

    /** 移除当前handler全部消息回调*/
    fun removeCallbacks() {
        MainHandler.removeCallbacksAndMessages(this)
    }


}